<?php
  class LwaCompiler {

    const BIN_DIR = 'LwaCompiler/bin/';
    const LOG_FOLDER = 'LwaCompiler/log';
    const LOG_FILE = 'compile.lua.txt';

    public static function compile($source, $prefix='', $cacheTime=0) {
      $name = md5($source);
      $folder = dirname(__FILE__).'/'.self::BIN_DIR.$prefix;
      if (!file_exists($folder)) {
        mkdir($folder, 0777, true);
      }
      $log_folder = dirname(__FILE__).'/'.self::LOG_FOLDER;
      if (!file_exists($log_folder)) {
        mkdir($log_folder, 0777, true);
      }

      $fileName = $folder.'/'.$name.'.lua';
      $fileBinName = $folder.'/'.$name;
      if (!file_exists($fileBinName)) {
        if (file_exists($fileName)) unlink($fileName);
        file_put_contents($fileName, $source);
        $descriptorspec = array(
          0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
          1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
          2 => array("pipe", "w"),  // stdout is a pipe that the child will write to
        );
        //$command = "java -jar ".dirname(__FILE__)."/LwaCompiler/LwaCompiler.jar $fileName $fileBinName";
        $command = "/usr/local/bin/luac -s -o $fileBinName $fileName";
        $process = proc_open($command, $descriptorspec, $pipes);
        $success = false;

        error_log($command."\n", 3, $log_folder.'/'.self::LOG_FILE);
        /*
        if (is_resource($process)) {
          $ret = true;
          while (!feof($pipes[1])) {
            $line = fgets($pipes[1],1024);
            if ($line) {
              error_log($line, 3, $log_folder.'/'.self::LOG_FILE);
            }
            if (trim($line)=='success') $success=true;
          }
          fclose($pipes[1]);
          proc_close($process);
        }
        */
        if (is_resource($process)) {
          $success=true;
          while (!feof($pipes[2])) {
            $line = fgets($pipes[2],1024);
            if ($line) {
              error_log($line, 3, $log_folder.'/'.self::LOG_FILE);
            }
            if (trim($line)!='') $success=false;
          }
          fclose($pipes[1]);
          proc_close($process);
        }

        if ($success) {
          file_put_contents($fileBinName, gzencode(file_get_contents($fileBinName), 9));
        }
      } else {
        $success = true;
      }

      if (!isset($_REQUEST['src'])) {
        header('Content-Type: gzip');
        if ($cacheTime>0) {
          header('cache: '.$cacheTime);
        }
        if ($success) {
          echo file_get_contents($fileBinName);
          exit();
        } else return null;
      } else {
        echo $source;
      }
    }
  }
